package com.shxy.cloudclassroom.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shxy.cloudclassroom.entity.dto.EditUserDTO;
import com.shxy.cloudclassroom.entity.dto.UserDTO;
import com.shxy.cloudclassroom.entity.pojo.*;
import com.shxy.cloudclassroom.entity.vo.DownloadHistoryVO;
import com.shxy.cloudclassroom.entity.vo.ViewHistoryVO;
import com.shxy.cloudclassroom.service.*;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

import static com.shxy.cloudclassroom.utils.SystemConstant.*;

/**
 * @Author 吴汇明
 * @School 绥化学院
 * @CreateTime 2025.10.16
 * 用户模块
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private OssService ossService;
    @Resource
    private LearningResourceService learningResourceService;
    @Resource
    private DownloadHistoryService downloadHistoryService;
    @Resource
    private ViewHistoryService viewHistoryService;
    @Resource
    private MajorService majorService;

    /**
     * 安全退出
     */
    @RequestMapping("logout")
    public String logout(HttpSession session) {
        session.invalidate(); //session失效
        return "redirect:/login";//跳转到登录界面
    }

    /**
     * 用户详情
     *
     * @param session
     * @param model
     * @return
     */

    @RequestMapping("/digital")
    public String digital(HttpSession session, Model model) {
        User userSession = (User) session.getAttribute(LOGIN_USER);
        User user = userService.query().eq("username", userSession.getUsername()).one();
        model.addAttribute(CURRENT_LOGIN_USER, user);
        return "individual";
    }

    /**
     * 更新用户信息
     * @param user 更新的用户信息
     * @param oldPassword 原密码
     * @param session 用户session
     * @return 成功或失败信息
     */
    @PostMapping("/update")
    @ResponseBody
    public Map<String, Object> updateUser(User user, 
                                         @RequestParam(required = false) String oldPassword,
                                         HttpSession session) {
        return userService.updateUser(user, oldPassword, session);
    }

    /**
     * 用户注册
     *
     * @return
     */
    @RequestMapping("register")
    public String register(UserDTO user, @RequestParam(value = "avatarUrl", required = false) String avatarUrl) {
        try {
            if (avatarUrl != null && !avatarUrl.isEmpty()) {
                user.setAvatar(avatarUrl);
            }
            userService.register(user);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return "redirect:/register";
        }
        return "redirect:/login";
    }

    /**
     * 头像上传
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadAvatar")
    @ResponseBody
    public String uploadAvatar(@RequestParam("avatar") MultipartFile file) {
        try {
            return userService.uploadAvatar(file);
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"error\":\"上传失败\"}";
        }
    }


    /**
     * 检查用户是否存在
     *
     * @param username
     * @return
     */
    @GetMapping("/check")
    @ResponseBody
    public String checkUser(@RequestParam String username) {
        log.debug("用户名:{}", username);
        return userService.checkUser(username);
    }

    @GetMapping("/code")
    @ResponseBody
    /**
     * 根据手机号生成验证码
     */
    public String sendCode(@RequestParam String username, HttpSession httpSession) {
        return userService.sendCode(username, httpSession);
    }

    /**
     * 浏览历史
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/history/views/{id}")
    public String viewHistory(@PathVariable Long id,
                              Model model) {
        List<ViewHistoryVO> historyVOS = userService.getViewHistory(id, learningResourceService, viewHistoryService, majorService);
        model.addAttribute(VIEW_HISTORY, historyVOS);
        return "/history/view";
    }

    /**
     * 下载历史
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/history/downloads/{id}")
    public String downloadHistory(@PathVariable Integer id,
                                  Model model) {
        List<DownloadHistoryVO> historyVOS = userService.getDownloadHistory(id, learningResourceService, downloadHistoryService, majorService);
        model.addAttribute(DOWNLOAD_HISTORY, historyVOS);
        return "/history/download";
    }
}
